<template>
<div class="commodityCardContainer" @mouseenter="enter" @mouseleave="leave">
  <div style="display: flex;justify-content: center">
    <img :src="commodityBean.img" width="200" style="text-align: center">
  </div>

  <span style="text-align: center;font-size: 14px">{{commodityBean.name}}</span>
  <span style="text-align: center;color: red">￥{{commodityBean.price}}</span>
  <button style="position: absolute;bottom: 5px;left: 65px;" v-show="showBtn" @click="add">加入到购物车中</button>
</div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {commodityModel} from "../../model/commodityModel";
import shoppingCartAPI from "../../api/shoppingCart";
import {userStore} from "../../store/userStore";
import {ElMessage} from "element-plus";
// import {commodityModel} from "../../model/commodityModel";

const userStoreImpl = userStore();

const props = defineProps({
  commodityBean: {
    required: true
  }
})

const showBtn = ref(false)

const enter = () => {
  showBtn.value = true;
}
const leave = () => {
  showBtn.value = false;
}
const elMessage = (isSuc: boolean) => {
  ElMessage({
    message: isSuc ? '添加到购物车成功' : '添加失败',
    type: isSuc ? 'success' : 'warn'
  })
}
const add = () => {
  if (userStoreImpl.user.id) {
    shoppingCartAPI.add(props.commodityBean.id, userStoreImpl.user.id)
        .then(res => {
          const data = res.data;
          if (data && data.code && data.code == 200) {
            elMessage(true);
          } else {
            elMessage(false);
          }
        })
  } else {
    elMessage(false);
  }
}
</script>

<style scoped>
.commodityCardContainer{
  width: 240px;
  height: 330px;
  background-color: #fff;
  border: 1px solid #f3f3f3;
  cursor: pointer;
  position: relative;
}
.commodityCardContainer>button>{

}
.commodityCardContainer:hover{
  border: 1px solid red;
}
</style>
